using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace UPA
{
    [Serializable]
    public class ProcessActionUnit:ISerializationCallbackReceiver
    {
        [SerializeField]
        private bool disabled;
        [SerializeReference]
        private string actionType;

        public string ActionType => actionType;

        public bool Disabled
        {
            get => disabled;
            set => disabled = value;
        }

        public ProcessAction Action { get; private set; }
        public string Name => GetName();
        
        public ProcessActionUnit(){}
        public ProcessActionUnit(ProcessAction action)
        {
            actionType = action.GetType().FullName;
            Action = action;
        }

        public void OnBeforeSerialize() { }

        private static Dictionary<string, Type> _typeCache = new();
        public void OnAfterDeserialize()
        {
            if (!_typeCache.TryGetValue(actionType, out var type))
            {
                var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes())
                    .Where(t => t.FullName == actionType).ToArray();
                if (types.Length == 0)
                {
                    Debug.LogError($"程序集中找不到类型:{actionType}");
                    return;
                }

                if (types.Length > 1)
                {
                    Debug.LogError($"当前项目中存在多个 {actionType}");
                    return;
                }
                type = types[0];
                _typeCache[actionType] = type;
            }

            if (Activator.CreateInstance(type) is not ProcessAction action)
            {
                Debug.LogError($"{actionType} 没有继承自 {nameof(ProcessAction)} 类型");
                
                return;
            }
            Action = action;
        }

        private string GetName()
        {
            return Action?.Name ?? actionType;
        }
    }
}